from django.shortcuts import render
from django.views import View
import os
from zipfile import ZipFile
import time
from PIL import Image
from djangoapp.settings import MEDIA_ROOT
from django.http import StreamingHttpResponse
# import cv2
# import requests


# Create your views here.
class deal_pic(View):

    def get(self, request):
        return render(request, 'tool/upload_files.html')

    def post(self, request):
        # 设置文件夹名称
        now_time = str(int(time.time()))
        dir_time_name = MEDIA_ROOT + "/" + now_time
        dir_time = dir_time_name + "/"

        if not os.path.exists(dir_time):
            os.mkdir(dir_time)
        # date_time = str(datetime.date.today().strftime('%y%m%d'))+str(de_time)

        files = request.FILES.getlist("file")
        size = int(request.POST.get("width"))
        # 判断客户端设备 True为手机 False为pc
        equipment = request.POST.get("equipment")
        # 保存原始图片到文件夹
        for file in files:
            # 保存图片
            # filename = file.filename.replace('"', '')
            # filename = secure_filename(file.filename)
            # file.save(secure_filename(file.filename))
            # file = cv2.imread(file.file)
            # cv2.imwrite(file, dir_time + file.name)
            save_path = dir_time + file.name
            with open(save_path, 'wb+')as f:
                for chunk in file.chunks():
                    f.write(chunk)

        # zip+处理图片
        with ZipFile(f"{dir_time_name}.zip", "w") as f:
            for root, dirs, filenames in os.walk(dir_time):
                # 压缩图片
                for file in filenames:
                    # print(file)
                    if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".gif") or file.endswith(".jpeg"):
                        input_file = str(root + file)

                        image = Image.open(input_file)
                        width = image.size[0]
                        height = image.size[1]
                        if width > height:
                            s = width / size
                        else:
                            s = height / size

                        if s != 0:
                            width_done = float(width) // s
                            height_done = float(width) // s
                            (width, height) = (int(width_done), int(height_done))
                            image_re = image.resize((width, height))
                            # 保存压缩图片
                            image_re.save(f"{dir_time + file}")
                            if equipment == "True":
                                response = StreamingHttpResponse(open(f"{dir_time + file}", 'rb'))
                                response['Content-Disposition'] = 'attachment;filename=' + f"{file}".encode(
                                    'utf-8').decode('ISO-8859-1')
                                return response
                            # 写入zip
                            f.write(dir_time + file)
        # 文件下载
        # wrapper = FileWarpper()
        response = StreamingHttpResponse(open(f"{dir_time_name}.zip", 'rb'))
        response['Content-Disposition'] = 'attachment;filename=' + f"{now_time}.zip".encode('utf-8').decode('ISO-8859-1')
        return response
        # return send_from_directory(app.config['UPLOAD_FOLDER'], f"{now_time}.zip", as_attachment=True)

